const recordBtn = document.querySelector(".chat-voice");

if (navigator.mediaDevices.getUserMedia) {
    var chunks = [];
    const constraints = {audio: true};
    navigator.mediaDevices.getUserMedia(constraints).then(
        stream => {
            const mediaRecorder = new MediaRecorder(stream);

            recordBtn.onclick = () => {
                if (mediaRecorder.state === "recording") {
                    mediaRecorder.stop();
                    recordBtn.innerHTML = '<i class="fa fa-volume-up" aria-hidden="true"></i>';
                } else {
                    mediaRecorder.start();
                    recordBtn.innerHTML = '<i class="fa fa-pause-circle" aria-hidden="true"></i>';
                }
            };

            mediaRecorder.ondataavailable = e => {
                chunks.push(e.data);
            };
            mediaRecorder.onstop = e => {
                var blob = new Blob(chunks, {type: "audio/ogg; codecs=opus"}),
                    //估算时长
                    duration = parseInt(blob.size / 6600);
                if (duration < 1) {
                    layer.open({
                        content: '说话时间太短!'
                        , time: 3
                        , skin: 'msg'
                    });
                    return;
                }

                chunks = [];
                var formData = new FormData();
                formData.append("file", blob);
                formData.append("sendMemberId", sendMemberId)
                formData.append("acceptMemberId", acceptMemberId)
                formData.append("duration", duration)
                $.ajax({
                    url: '/uploadVoice',
                    type: 'post',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function (msg) {
                        renderingVoice(msg.data)
                        playSendMsgSound();
                    }
                });
            };
        },
        () => {
            layer.open({
                content: '请授权录音权限!否则无法使用语音功能'
                , time: 3
                , skin: 'msg'
            });
        }
    );
} else {
    layer.open({
        content: '浏览器不支持 getUserMedia'
        , time: 3
        , skin: 'msg'
    });

}

// 渲染语音
function renderingVoice(msg) {
    $(".chatBox-content-demo").append("<div class=\"clearfloat\">" +
        "<div class=\"author-name\"><small class=\"chat-date\">" + sendTime() + "</small> </div> " +
        "<div class=\"right\"> <div class=\"chat-message\">" + msg + "</div>" +
        "<div class=\"chat-avatars\"><img src=" + sendAvatarUrl + " alt=\"头像\" /></div> </div> </div>");
    //聊天框默认最底部
    chatBottom();
}

// 播放语音
function playAudio(e) {
    if (e.lastElementChild.paused) {
        e.lastElementChild.play()
    } else {
        e.lastElementChild.pause();
    }
}